﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U9.Base.Doc;
using UFIDA.U9.CBO.SCM.Enums;
using UFIDA.U9.Cust.YYD.PlugBE.Dtos;
using UFIDA.U9.Cust.YYD.PlugBE.Public;
using UFIDA.U9.PM.ASN;
using UFIDA.U9.PM.PO;
using UFIDA.U9.SM.ShipPlan;
using UFIDA.U9.SM.SO;
using UFSoft.UBF.Business;

namespace UFIDA.U9.Cust.YYD.PlugBE.ShipPlanP
{
    public class AfterUpdating : UFSoft.UBF.Eventing.IEventSubscriber
    {
        public void Notify(params object[] args)
        {
            #region 从事件参数中取得当前业务实体													 
            if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
                return;
            BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
            if (key == null)
                return;
            var holder = key.GetEntity() as UFIDA.U9.SM.ShipPlan.ShipPlan;
            if (holder == null)
                return;
            #endregion
            //审核
            if (holder.Status == SM.ShipPlan.ShipPlanDocStatusEnum.Posted && holder.OriginalData.Status == SM.ShipPlan.ShipPlanDocStatusEnum.Posting)
            {
              

                HttpHelper httpHelper = new HttpHelper();
                JsonConfig config = new JsonConfig();
                httpHelper.URL = config.SelectToken("WMS.URL") + "/openapi/v3/receipt/create-delivery-note";



                List<ShipPlanLine> ShipPlanLines = holder.ShipPlanLines.Cast<ShipPlanLine>().ToList();


                foreach (var lines in ShipPlanLines.GroupBy(m => m.SrcDoc))
                {

                    SO so = SO.Finder.FindByID(lines.FirstOrDefault().SrcDoc);

                    if (so != null)
                    {
                        DeliveryNoteCreateOpenV3Req dto = new DeliveryNoteCreateOpenV3Req();

                        dto.tenantId = "1";
                        dto.sourceSysType = "ERP";
                        dto.billGroupCode = "XSC01";
                        if (so.DocumentType.Code == "SO3")
                        {
                            dto.billTypeCode = "XSC01-02";
                        }
                        else
                        {
                            dto.billTypeCode = "XSC01-01";
                        }

                        dto.billSourceCode = so.DocumentType.Code;
                        dto.billSourceText = so.DocumentType.Name;
                        dto.billSourceNumber = holder.DocNo;
                        dto.urgencyDegree = "NORMAL";
                        dto.targetType = "TARGET_CUSTOMER";
                        dto.targetCode = so.OrderBy.Customer.Code;
                        dto.plannedTime = so.BusinessDate.ToString();
                        dto.completionTime = so.BusinessDate.ToString();
                        dto.remark = so.Memo;

                        List<DeliveryRequirementCreateOpenReq> dtolines = new List<DeliveryRequirementCreateOpenReq>();

                        foreach (var line in lines)
                        {

                            SOLine soline = SOLine.Finder.FindByID(line.SrcDocLine);

                            DeliveryRequirementCreateOpenReq dtoit = new DeliveryRequirementCreateOpenReq();
                            dtoit.materialCode = soline.ItemInfo.ItemCode;
                            dtoit.customerCode = so.OrderBy.Customer.Code;
                            dtoit.batchNo = soline.SOShiplines[0]?.Lot?.LotCode??"";
                            dtoit.warehouseCode = line.WH?.Code ?? "";
                            dtoit.productionDate = so.BusinessDate.ToString();
                            dtoit.entryTime = so.BusinessDate.ToString();
                            dtoit.qualityLevel = "QUALIFIED_PRODUCT";
                            dtoit.lineNumber = soline.DocLineNo.ToString();
                            dtoit.plannedQuantity = soline.OrderByQtyTU;
                            dtoit.barcodeQuantity = soline.OrderByQtyTU;
                            dtoit.sourceBillCode = holder.DocNo;
                            dtoit.sourceDetailLineNumber = line.DocLineNo.ToString();
                            dtolines.Add(dtoit);
                        }

                        dto.requirements = dtolines;

                        httpHelper.Content = JsonConvert.SerializeObject(dto);
                        var result = JObject.Parse(httpHelper.HttpPosts("POST"));
                        if (result["code"].ToString() != "000000")
                        {
                            throw new Exception(result["msg"].ToString());
                        }
                    }
                }

            }

            //弃审
            if (holder.Status == SM.ShipPlan.ShipPlanDocStatusEnum.Open && holder.OriginalData.Status == SM.ShipPlan.ShipPlanDocStatusEnum.Posted)
            {
                HttpHelper httpHelper = new HttpHelper();
                JsonConfig config = new JsonConfig();
                httpHelper.URL = config.SelectToken("WMS.URL") + "/openapi/v3/receipt/delete-delivery-note";


                WMSDeleteDTO dto = new WMSDeleteDTO();
                dto.billSourceNumber = holder.DocNo;

                httpHelper.Content = JsonConvert.SerializeObject(dto);
                var result = JObject.Parse(httpHelper.HttpPosts("POST"));
                if (result["code"].ToString() != "000000")
                {
                    throw new Exception(result["msg"].ToString());
                }
            }
        }
    }
}
